package com.baidu.structure.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.baidu.structure.bean.InviteInfoBean;
import com.baidu.structure.db.DBManager;
import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;

/**
 * Created by sunmo on 2016/10/24.
 */
public class ConfigUtils {
    private static SharedPreferences sp;
    public static final String FILENAME = "config";
    private static Context mContext;

    private boolean isContactRegistered = false;

    private ConfigUtils() {
    }

    //get a default preference edit
    public static ConfigUtils getDefaultInstance(Context context) {
        sp = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        mContext = context;
        return new ConfigUtils();
    }

    /**
     * preference related
     */
    //get a preference instance
    public static ConfigUtils getInstance(String fileName, Context context) {
        sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        return new ConfigUtils();
    }

    //write
    public void write(String key, String value) {
        sp.edit().putString(key, value).commit();
    }

    //readString
    public String readString(String key) {
        return sp.getString(key, null);
    }

    //read int
    public int readInt(String key) {
        return sp.getInt(key, 0);
    }


    /**
     * huanxin related
     * register EM listener
     */
    public void registerEMListener() {
        if (!isContactRegistered) {
            EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
            isContactRegistered = true;
        }
    }

    //monitor contact changes
    class MyContactListener implements EMContactListener {
        /**
         * @param s userName
         *          sl  reason
         */
        @Override
        public void onContactAdded(String s) {

        }

        @Override
        public void onContactDeleted(String s) {

        }

        @Override
        public void onContactInvited(String s, String s1) {
            InviteInfoBean b = new InviteInfoBean();
            b.setFromName(s);
            b.setReason(s1);
            DBManager.getInstance(mContext).insertInviteInfo(b);
        }

        @Override
        public void onContactAgreed(String s) {
            DBManager.getInstance(mContext).deleteInviteInfo(s);
        }

        @Override
        public void onContactRefused(String s) {
            DBManager.getInstance(mContext).deleteInviteInfo(s);
        }
    }
}
